<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2019 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: Forpastime < forpastime@qq.com>
// +----------------------------------------------------------------------
namespace app\tenant_user\controller;

use cmf\controller\AdminBaseController;
use app\admin\model\AdminMenuModel;
use app\partner\model\AreaModel;
use app\tenant_user\model\UserModel;
use think\Db;

/**
 * Class AdminIndexController
 * @package app\tenant_user\controller
 * @adminMenuRoot(
 *     'name'   =>'商户用户管理',
 *     'action' =>'default',
 *     'parent' =>'',
 *     'display'=> true,
 *     'order'  => 30,
 *     'icon'   =>'user',
 *     'remark' =>'商户用户管理'
 * )
 */
class AdminIndexController extends AdminBaseController
{
    /**
     * 用户管理
     * @adminMenu(
     *     'name'   => '用户管理',
     *     'parent' => 'tenant_user/AdminIndex/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 20,
     *     'icon'   => '',
     *     'remark' => '用户管理',
     *     'param'  => ''
     * )
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $admin_id = cmf_get_current_admin_id();
        $admin = Db::name('user')->where('id',$admin_id)->find();
        
        $tenent_id = $admin['tenant_id']==0?$admin_id:$admin['tenant_id'];
        $shop_id = Db::name('shop_apply_order')->where('user_id',$tenent_id)->value('shop_info_id');
        $username = $this->request->param('name');
        $area = $this->request->param('area_value');

        $user = new UserModel();


        $role = Db::name("role_user")->where("user_id", $admin_id)->where('role_id','in',[1,2])->select()->toArray();

        if($admin_id==1 || !empty($role)){
            $filter = [];
        }else{
            
            $filter = [
                'shop_info_id'=>$shop_id
            ];
        }
        
        $list = $user->getList($filter,'id desc',$username,$area);

        $this->assign('users',$list);
        // 获取分页显示
        $page = $list->render();
        $this->assign("page", $page);

        return $this->fetch();
    }

    /**
     * 商户客户管理
     * @adminMenu(
     *     'name'   => '添加客户',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 20,
     *     'icon'   => '',
     *     'remark' => '添加客户',
     *     'param'  => ''
     * )
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function add()
    {
        $admin_id = cmf_get_current_admin_id();
        $user = Db::name("user")->where("id", $admin_id)->find();

        $tenant_id = $user['tenant_id']==0?$admin_id:$user['tenant_id'];
        $category = Db::name('tenant_user_category')->where('tenant_id',$tenant_id)->where('status',1)->select();
        
        $this->assign('tenant_id',$tenant_id);

        $this->assign('category',$category);

        $this->assign('admin',$user);
        $area = new AreaModel();
        $province = $area->province();
        $this->assign('province',$province);
        return $this->fetch();
    }

    /**
     * 商户客户添加提交
     * @adminMenu(
     *     'name'   => '商户客户添加提交',
     *     'parent' => 'add',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 20,
     *     'icon'   => '',
     *     'remark' => '商户客户添加提交',
     *     'param'  => ''
     * )
     */
    public function addPost()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param('post');
            $tag_id = $this->request->param('tag_id');
            $tag = '';

            if(!empty($tag_id)){
                foreach($tag_id as $k => $v){
                    if($k==0){
                        $tag .=$v; 
                    }else{
                        $tag .=','.$v; 
                    }
                }
            }
            $user = [
                'tenant_id'=>$param['tenant_id'],
                'name'=>$param['name'],
                'age'=>$param['age'],
                'tel'=>$param['tel'],
                'wechat_id'=>$param['wechat_id'],
                'sex'=>$param['sex'],
                'tag_id'=>$tag,
                // 'category_id'=>$param['category_id'],
                'area_key'=>$param['province'].','.$param['city'].','.$param['country'],
                'area_value'=>$param['province_name'].','.$param['city_name'].','.$param['country_name']
            ];
             $res = Db::name('tenant_user')->insertGetId($user);

             if($res){
                $this->success("添加成功");
             }else{
                $this->error("添加失败");
             }
             
        }
    }
    /**
     * 商户客户管理
     * @adminMenu(
     *     'name'   => '修改客户',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 20,
     *     'icon'   => '',
     *     'remark' => '修改客户',
     *     'param'  => ''
     * )
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function edit()
    {
        $admin_id = cmf_get_current_admin_id();
        $user = Db::name("user")->where("id", $admin_id)->find();

        $category = Db::name('tenant_user_category')->where('tenant_id',$user['tenant_id']==0?$admin_id:$user['tenant_id'])->where('status',1)->select();

        $this->assign('category',$category);

        $this->assign('admin',$user);
        $area = new AreaModel();
        $province = $area->province();
        $this->assign('province',$province);

        $id =$this->request->param('id',0,'intval');
        $tenant_user = Db::name('tenant_user')->where('id',$id)->find();

        $tags = explode(',',$tenant_user['tag_id']);

        $this->assign('tags',$tags);

        $this->assign('tenant',$tenant_user);

        return $this->fetch();
    }
        /**
     * 商户客户修改提交
     * @adminMenu(
     *     'name'   => '商户客户修改提交',
     *     'parent' => 'edit',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 20,
     *     'icon'   => '',
     *     'remark' => '商户客户修改提交',
     *     'param'  => ''
     * )
     */
    public function editPost()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param('post');
            $tag_id = $this->request->param('tag_id');
            $tag = '';

            if(!empty($tag_id)){
                foreach($tag_id as $k => $v){
                    if($k==0){
                        $tag .=$v; 
                    }else{
                        $tag .=','.$v; 
                    }
                }
            }
            $user = [
                'name'=>$param['name'],
                'age'=>$param['age'],
                'tel'=>$param['tel'],
                'wechat_id'=>$param['wechat_id'],
                'sex'=>$param['sex'],
                'tag_id'=>$tag,
                'category_id'=>$param['category_id']
            ];
            if(!empty($param['province']) && !empty($param['city'])){
                $user['area_key']=$param['province'].','.$param['city'].','.$param['country'];
                $user['area_value']=$param['province_name'].','.$param['city_name'].','.$param['country_name'];
            }
             $res = Db::name('tenant_user')->where('id',$param['id'])->update($user);

             if($res){
                $this->success("修改成功");
             }else{
                $this->error("修改失败");
             }
             
        }
    }
    /**
     * 商户用户删除
     * @adminMenu(
     *     'name'   => '商户用户删除',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 20,
     *     'icon'   => '',
     *     'remark' => '商户用户删除',
     *     'param'  => ''
     * )
     */
    public function delete()
    {
        $param = $this->request->param();
        $res = Db::name('tenant_user')->where('id',$param['id'])->update(['status'=>0]);

        if($res){
            $this->success("删除成功");
        }else{
            $this->error("删除失败");
        }
    }
    /**
     * 员工管理
     * @adminMenu(
     *     'name'   => '员工管理',
     *     'parent' => 'tenant_user/AdminIndex/default',
     *     'display'=> true,
     *     'hasView'=> true,
     *     'order'  => 20,
     *     'icon'   => '',
     *     'remark' => '员工管理',
     *     'param'  => ''
     * )
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function staff()
    {
        $param = $this->request->param();
        $admin_id = cmf_get_current_admin_id();
        $admin = Db::name('user')->where('id',$admin_id)->find();

        $tenent_id = $admin['tenant_id']==0?$admin_id:$admin['tenant_id'];
        
        $list = Db::name('tenant_staff')->alias('s')
            ->leftJoin('tenant_staff_category c',['s.category_id = c.id'])
            ->field('s.*,c.name as category_name')
            ->where('s.status',1)
            ->where('s.tenant_id',$tenent_id)
            ->order('s.id desc')
            ->paginate(10);
        $list->appends($param);;

        $this->assign('users',$list);
        // 获取分页显示
        $page = $list->render();
        $this->assign("page", $page);

        return $this->fetch();
    }



        /**
     * 添加客户跟进记录
     * @adminMenu(
     *     'name'   => '添加客户跟进记录',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 20,
     *     'icon'   => '',
     *     'remark' => '添加客户跟进记录',
     *     'param'  => ''
     * )
     */
    public function addRecord()
    {
        $param = $this->request->param();
        $admin_id = cmf_get_current_admin_id();
        $user = Db::name("user")->where("id", $admin_id)->find();

        $data = [
            'user_id'=>$param['user_id'],
            'content'=>$param['content'],
            'record_manager'=>$user['user_nickname'],
            'tenant_id'=>$user['tenant_id']==0?$admin_id:$user['tenant_id'],
            'create_time'=>time(),
            'update_time'=>time()
        ];
        $res = Db::name('tenant_user_records')->insertGetId($data);

        if($res){
            Db::name('tenant_user')->where('id',$param['user_id'])->setInc('communicate_times');
            $this->success('添加成功');
        }else{
            $this->error('添加失败');
        }
    }

    /**
     * 修改客户跟进记录
     * @adminMenu(
     *     'name'   => '修改客户跟进记录',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 20,
     *     'icon'   => '',
     *     'remark' => '修改客户跟进记录',
     *     'param'  => ''
     * )
     */
    public function editRecord()
    {
        $param = $this->request->param();
        $admin_id = cmf_get_current_admin_id();
        $user = Db::name("user")->where("id", $admin_id)->find();

        $data = [
            'content'=>$param['msg'],
            'record_manager'=>$user['user_nickname'],
            'tenant_id'=>$user['tenant_id']==0?$admin_id:$user['tenant_id'],
            'update_time'=>time()
        ];
        $res = Db::name('tenant_user_records')->where('id',$param['id'])->update($data);

        if($res){
            $this->success('修改成功');
        }else{
            $this->error('修改失败');
        }
    }
    
    /**
     * 客户跟进记录
     * @adminMenu(
     *     'name'   => '客户跟进记录',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 20,
     *     'icon'   => '',
     *     'remark' => '客户跟进记录',
     *     'param'  => ''
     * )
     */
    public function records()
    {
        $param = $this->request->param();
        $admin_id = cmf_get_current_admin_id();
        $user = Db::name("user")->where("id", $admin_id)->find();

        $records = Db::name('tenant_user_records')
            ->where('tenant_id',$user['tenant_id']==0?$admin_id:$user['tenant_id'])
            ->where('user_id',$param['id'])
            ->order('create_time desc')
            ->paginate(10);
        $records->appends($param);

        $page = $records->render();

        $this->assign("user_id",$param['id']);
        $this->assign("page",$page);
        $this->assign("records",$records);

        return $this->fetch();
    }
    
    /**
     * 商户员工管理
     * @adminMenu(
     *     'name'   => '添加员工',
     *     'parent' => 'staff',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 20,
     *     'icon'   => '',
     *     'remark' => '添加员工',
     *     'param'  => ''
     * )
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function addStaff()
    {
        
        $category = Db::name('tenant_staff_category')->where('status',1)->select();

        $this->assign('category',$category);

        return $this->fetch();
    }

    /**
     * 商户员工管理
     * @adminMenu(
     *     'name'   => '修改员工',
     *     'parent' => 'staff',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 20,
     *     'icon'   => '',
     *     'remark' => '修改员工',
     *     'param'  => ''
     * )
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function editStaff()
    {
        $param = $this->request->param();
        $category = Db::name('tenant_staff_category')->where('status',1)->select();

        $this->assign('category',$category);

        $staff = Db::name('tenant_staff')->where('id',$param['id'])->find();

        if(!empty($staff['professional_certificates'])){
            $this->assign('professional_certificates',explode(',',$staff['professional_certificates']));

        }
        $this->assign('identification',json_decode($staff['identification']));

        $this->assign('staff',$staff);

        return $this->fetch();
    }

    /**
     * 商户员工添加提交
     * @adminMenu(
     *     'name'   => '商户员工添加提交',
     *     'parent' => 'addStaff',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 20,
     *     'icon'   => '',
     *     'remark' => '商户员工添加提交',
     *     'param'  => ''
     * )
     */
    public function addStaffPost()
    {
        if ($this->request->isPost()) {
            $admin_id = cmf_get_current_admin_id();
            $user = Db::name("user")->where("id", $admin_id)->find();

            $param = $this->request->param('post');
            $identification = $this->request->param('identification');

            $user = [
                'name'=>$param['name'],
                'social_work_age'=>$param['social_work_age'],
                'tel'=>$param['tel'],
                'professional_title'=>$param['professional_title'],
                'sex'=>$param['sex'],
                'good_at'=>empty($param['good_at'])?'':$param['good_at'],
                'category_id'=>$param['category_id'],
                'create_time'=>time(),
                'tenant_id'=>$user['tenant_id']==0?$admin_id:$user['tenant_id'],
                'identification'=>json_encode($identification)
            ];

            $photo_urls = $this->request->param('photo_urls');
            if(!empty($photo_urls)){
                $user['avatar'] = cmf_get_image_preview_url($photo_urls[0]);
            }

            $cert_urls = $this->request->param('cert_urls');
            $certificates='';
            if(!empty($cert_urls)){
                foreach($cert_urls as $k=> $v){
                    if($k!=0){
                        $certificates = $certificates.','. cmf_get_image_preview_url($v);

                    }else{
                        $certificates = cmf_get_image_preview_url($v);

                    }
                }
                $user['professional_certificates'] = $certificates;
            
            }
             $res = Db::name('tenant_staff')->insertGetId($user);

             if($res){
                $this->success("添加成功");
             }else{
                $this->error("添加失败");
             }
             
        }
    }

        /**
     * 商户员工修改提交
     * @adminMenu(
     *     'name'   => '商户员工修改提交',
     *     'parent' => 'editStaff',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 20,
     *     'icon'   => '',
     *     'remark' => '商户员工修改提交',
     *     'param'  => ''
     * )
     */
    public function eidtStaffPost()
    {
        if ($this->request->isPost()) {
            $param = $this->request->param('post');
            $identification = $this->request->param('identification');
            $user = [
                'name'=>$param['name'],
                'social_work_age'=>$param['social_work_age'],
                'tel'=>$param['tel'],
                'professional_title'=>$param['professional_title'],
                'sex'=>$param['sex'],
                'good_at'=>empty($param['good_at'])?'':$param['good_at'],
                'category_id'=>$param['category_id'],
                'identification'=>json_encode($identification)
            ];

            $photo_urls = $this->request->param('photo_urls');
            if(!empty($photo_urls)){
                $user['avatar'] = cmf_get_image_preview_url($photo_urls[0]);
            }

            $cert_urls = $this->request->param('cert_urls');
            $certificates='';
            if(!empty($cert_urls)){
                foreach($cert_urls as $k=> $v){
                    if($k!=0){
                        $certificates = $certificates.','. cmf_get_image_preview_url($v);

                    }else{
                        $certificates = cmf_get_image_preview_url($v);

                    }
                }
                $user['professional_certificates'] = $certificates;
            
            }
             $res = Db::name('tenant_staff')->where('id',$param['id'])->update($user);

             if($res){
                $this->success("修改成功");
             }else{
                $this->error("修改失败");
             }
             
        }
    }
    /**
     * 商户员工删除
     * @adminMenu(
     *     'name'   => '商户员工删除',
     *     'parent' => 'editStaff',
     *     'display'=> false,
     *     'hasView'=> false,
     *     'order'  => 20,
     *     'icon'   => '',
     *     'remark' => '商户员工删除',
     *     'param'  => ''
     * )
     */
    public function deleteStaff()
    {
        $param = $this->request->param();
        $res = Db::name('tenant_staff')->where('id',$param['id'])->update(['status'=>0]);

        if($res){
            $this->success("删除成功");
        }else{
            $this->error("删除失败");
        }
    }
}